﻿var viewModel = new function () {
    this.data = ko.observableArray(data.LeadSource);
    this.CurrentPageIndex = ko.observable(1);
    this.PageSize = ko.observable(10);

    this.SetOrder = SetOrder;

    this.ColName = ko.observable("Title");
    this.SortOrder = ko.observable("asc");
    this.MaxPageIndex = ko.computed(function () {
        return Math.ceil(ko.utils.unwrapObservable(this.data()).length / this.PageSize());
    }, this);

    this.leadSources = ko.computed(function () {
        var pagevalue = this.PageSize().toString().replace(/\s/g, '');
        var pagesize = parseInt(pagevalue, 10);

        if (pagesize.toString() == 'NaN' || pagesize < 1 || pagesize > 100) {
            return "";
        }
        else {
            var startIndex = this.PageSize() * (this.CurrentPageIndex() - 1);
            var endIndex = parseInt(startIndex) + parseInt(this.PageSize());

            return this.data().slice(startIndex, endIndex);
        }
    }, this);

    ///////////////////// Paging /////////////////////////////
    this.PageSizeText = ko.computed(function () {

        var pagevalue = this.PageSize().toString().replace(/\s/g, '');
        var pagesize = parseInt(pagevalue, 10);
        this.CurrentPageIndex(1);
        if (!IsNumeric(pagevalue))
            return "* Please enter a number between 1 - 100";
        else if (pagesize.toString() == 'NaN' || pagesize < 1 || pagesize > 100) {
            return "* Please enter a number between 1 - 100";
        }
        else {
            return "";
        }

    }, this);
    this.PageCurrentText = ko.computed(function () {
        var pagevalue = this.CurrentPageIndex().toString().replace(/\s/g, '');
        var pageindex = parseInt(pagevalue, 10);

        if (!IsNumeric(this.CurrentPageIndex()) || pagevalue == "")
            return "* Please enter a number between 1 - " + this.MaxPageIndex() + " ";
        else if (pagevalue.toString() == 'NaN' || !IsNumeric(pagevalue) || pageindex < 1 || pageindex > this.MaxPageIndex()) {
            return "* Please enter a number between 1 - " + this.MaxPageIndex() + " ";
        }
        else {
            return "";
        }

    }, this);

    this.PrevPage = function () {
        var page = parseInt(this.CurrentPageIndex());
        if (page > 1) {
            this.CurrentPageIndex(page - 1);
        }
    }
    this.NextPage = function () {
        var page = parseInt(this.CurrentPageIndex());
        if (page < this.MaxPageIndex()) {
            this.CurrentPageIndex(page + 1);
        }
    }

    this.PrevButtonClass = ko.computed(function () {
        var page = parseInt(this.CurrentPageIndex());
        return (page > 1) ? "btn btn-prev-arrow prev-active" : "btn btn-prev-arrow";
    }, this);

    this.NextButtonClass = ko.computed(function () {
        if (this.CurrentPageIndex() == this.MaxPageIndex() || this.MaxPageIndex() == 1)
            return "btn btn-next-arrow next-disabled";
        else
            return "btn btn-next-arrow";
    }, this);

    // PageSize/ PageCurrent keypress enter
    this.RunSomethingKey = function (viewModel, event) {
        if (event.keyCode == 13) {
            this.RunSomething(viewModel, event);
        }
        return true;
    }

    this.RunSomething = function (viewModel, event) {
        return true;
        LoadDataKeyPresss();
    }

    function LoadDataKeyPresss() {
        // Page Size
        var pageSizeValue = $('#pagesize').val().toString().replace(/\s/g, '');
        var pagesize = parseInt(pageSizeValue, 10);
        if (!IsNumeric(pageSizeValue) || pagesize.toString() == 'NaN' || pagesize < 1 || pagesize > 100) {
            return false;
        }

        // Page Index
        var pageIndexValue = $('#pagecurrent').val().toString().replace(/\s/g, '');
        var pageindex = parseInt(pageIndexValue, 10);
        if (!IsNumeric(pageIndexValue) || pageindex.toString() == 'NaN' || pageindex < 1 || pageindex > viewModel.MaxPageIndex()) {
            return false;
        }
    }

    //////////////////////////////// Event ///////////////////////////////////

    this.DeleteLeadSource = function () {
        var leadId = $('#leadSourceIdPopup').val();

        var dataPost = { "id": leadId };
        var urlPost = "/LeadSource/Delete";

        closeDeleteConfirm();
        openProcess();
        $.ajax({ type: "POST", url: urlPost, data: dataPost, dataType: "json",
            success: function (data, textStatus, jqXHR) {
                if (data.Error == undefined || data.Error == null) {
                    for (var i = 0; i < viewModel.data().length; i++) {
                        if (viewModel.data()[i].LeadSourceId == leadId) {
                            //Remove item here
                            viewModel.data.splice(i, 1);
                            break;
                        }
                    }
                    closeDeleteConfirm();
                    hideProcess();

                }
                else {
                    showPopupError();
                }
            },
            error: function (xhr, status, error) {
                // Stop progress bar
                $('.waiting').hide();
                $('#progress').css("display", "none");
                showPopupError();
            }
        }); // End ajax post

    };

    ////// Sorting ///////
    function SetTHClass(event, colName) {
        $("div.title").parent().find(".sort_wrapper").children("span").removeClass("asc");
        $("div.title").parent().find(".sort_wrapper").children("span").removeClass("desc");

        if (viewModel.SortOrder() === "asc") {
            $("#" + colName).children("span").addClass("asc");
        } else {
            $("#" + colName).children("span").addClass("desc");
        }
    }

    function SwitchSortOrder() {
        if (this.SortOrder() === "asc") {
            this.SortOrder("desc");
        } else {
            this.SortOrder("asc");
        }
    }
    this.SwitchSortOrder = SwitchSortOrder;

    function SetOrder(event, ColName) {
        if (this.ColName() === ColName) {
            this.SwitchSortOrder();
        } else {
            this.ColName(ColName);
            this.SortOrder("asc");
        }
        SetTHClass(event, ColName);

        if (ColName != "") {
            this.data(SortByPropertyName(ko.utils.unwrapObservable(this.data()), ColName, this.SortOrder()));
        }
    }

    // sort all items
    function SortByPropertyName(items, propertyName, sortOrder) {
        return items.sort(sortProperty(propertyName, sortOrder));
    }
    function sortProperty(property, sortOrder) {
        if (sortOrder == "asc") {
            return function (a, b) {
                var number;
                if (property == "InboundPhone") {
                    return (a[property].toLowerCase() < b[property].toLowerCase()) ? -1 : (a[property].toLowerCase() > b[property].toLowerCase()) ? 1 : 0;
                }
                else {

                    if ($.isNumeric(a[property])) {
                        number = parseFloat(a[property]);
                    } else {
                        number = parseFloat(a[property].toLowerCase());
                    }
                    if (number != NaN && number > 0)
                        return (parseFloat(a[property]) < parseFloat(b[property])) ? -1 : (parseFloat(a[property]) > parseFloat(b[property])) ? 1 : 0;
                    else
                        return (a[property].toLowerCase() < b[property].toLowerCase()) ? -1 : (a[property].toLowerCase() > b[property].toLowerCase()) ? 1 : 0;

                }
            }
        }
        else {
            return function (a, b) {
                var number;
                if (property == "InboundPhone") {
                    return (a[property].toLowerCase() > b[property].toLowerCase()) ? -1 : (a[property].toLowerCase() < b[property].toLowerCase()) ? 1 : 0;
                }
                else {

                    if ($.isNumeric(a[property])) {
                        number = parseFloat(a[property]);
                    } else {
                        number = parseFloat(a[property].toLowerCase());
                    }
                    if (number != NaN && number > 0)
                        return (parseFloat(a[property]) > parseFloat(b[property])) ? -1 : (parseFloat(a[property]) < parseFloat(b[property])) ? 1 : 0;
                    else
                        return (a[property].toLowerCase() > b[property].toLowerCase()) ? -1 : (a[property].toLowerCase() < b[property].toLowerCase()) ? 1 : 0;
                }
            }
        }
    }
}

ko.applyBindings(viewModel, document.getElementById("main"));

function OpenDeleteLeadSource(_leadSourceId) 
{   
    var dataPost = { "id": _leadSourceId };
    var urlPost = "/LeadSource/IsLeadSourceDeleteable";

    $.ajax({ type: "POST", url: urlPost, data: dataPost, dataType: "json",
        success: function (data, textStatus, jqXHR) {
            if (data == "") {  // Can delete
                $('#leadSourceNamePopup1').text($('#leadSourceId' + _leadSourceId).attr("rel"));
                $('#leadSourceIdPopup').val(_leadSourceId);
                $('#confirmDelete').showPopup({
                    width: 480
                });
                $('#fancybox-overlay').show();
            }
            else { // Associated
                $('#leadSourceNamePopup2').text($('#leadSourceId' + _leadSourceId).attr("rel"));
                $('#associatedSource').showPopup({
                    width: 480
                });
                $('#fancybox-overlay').show();
            }
        },
        error: function (xhr, status, error) {
            showPopupError();
        }
    });
   
}

function closeConfirm() {
    $('#confirmDelete').hide();
    $('#fancybox-overlay').hide();
    $(".fancybox-wrap").hide();
}

function closeDeleteConfirm() {
    $('#confirmDelete').hide();
    $('#fancybox-overlay').hide();
    $(".fancybox-wrap").hide();
}